from app.db.mongoClient import ErrMongoClient, get_mongo_client
from . import dbSynPosDishes, collectionDishList, collectionImageList
from app.globals.uuidTool import getuuId
from app.globals.publicMethod import globalGetNowTime, globalStrMd5, globalBase64ImageScale

def createDish(diningNo, stallNo, dishName, dishPrice, 
            dishUnit, classNames, menuNames, dishDesc, imageSrc):
    '''
     创建新菜品
    '''
    try:
        imageId = ''
        if len(imageSrc) > 200:
            imageSrc = globalBase64ImageScale(imageSrc)
            imageId = globalStrMd5(imageSrc)

        mg_client = get_mongo_client()
        cond = {'diningNo': diningNo, 'stallNo': stallNo}
        collection = mg_client[dbSynPosDishes][collectionDishList]
        res = collection.find_one(cond)
        newList = []
        # 如果餐厅和档口号不存在该表中
        if res is None:
            dishId = getuuId()
            now = globalGetNowTime()
            dishdata = {
                'dishId': dishId,
                'dishName': dishName,
                'dishPrice': dishPrice,
                'dishDesc': dishDesc,
                'dishState': 'stay',
                'checkFailDesc': '',
                'dishUnit': dishUnit, 
                'dishSort': 1,
                'createTime': now,
                'updateTime': now,   
                'menuNames': menuNames,
                'classNames': classNames,   
                'imageId': imageId
            }
            newList.append(dishdata)
            data = {
                'diningNo': diningNo,
                'stallNo': stallNo,
                'dishList': newList
            }
            collection.insert_one(data)
            # 把该图片插入imageList集合里
            collectionImage = mg_client[dbSynPosDishes][collectionImageList]
            imageInfo = {
                'imageId': imageId,
                'imageSrc': imageSrc
            }
            collectionImage.insert_one(imageInfo)
            return dishId

        # 如果餐厅和档口存在该表中
        tempres = res.get('dishList')
        if tempres is not None:
            if len(tempres) > 0:
                newList = tempres
                for v in tempres:
                    if v['dishName'] == dishName:
                        return False # 该菜名已存在

        dishId = getuuId()
        now = globalGetNowTime()
        data = {
            'dishId': dishId,
            'dishName': dishName,
            'dishPrice': dishPrice,
            'dishDesc': dishDesc,
            'dishState': 'stay',
            'checkFailDesc': '',
            'dishUnit': dishUnit,
            'dishSort': 1,
            'createTime': now,
            'updateTime': now,   
            'menuNames': menuNames,
            'classNames': classNames,
            'imageId': imageId
        }

        newList.append(data)
        collection.find_one_and_update(cond, 
                    {'$set': 
                        {'dishList': newList} 
                    })

        # 把该图片插入imageList集合里
        collectionImage = mg_client[dbSynPosDishes][collectionImageList]
        imageInfo = {
            'imageId': imageId,
            'imageSrc': imageSrc
        }
        collectionImage.insert_one(imageInfo)

        return dishId
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def createBatchDish(diningNo, stallNo, dishList):
    '''
     批量创建档口菜品
    '''
    try:
        mg_client = get_mongo_client()
        cond = {'diningNo': diningNo, 'stallNo': stallNo}
        collection = mg_client[dbSynPosDishes][collectionDishList]
        res = collection.find_one(cond)
        newList = []
        dishIdList = []
        # 如果餐厅和档口号不存在该表中
        if res is None:
            for dish in dishList:
                dishId = getuuId()
                now = globalGetNowTime()
                imageSrc = dish.get('imageSrc')
                imageId = ''
                if imageSrc is not None and len(imageSrc) > 200:
                    imageSrc = globalBase64ImageScale(imageSrc)
                    imageId = globalStrMd5(imageSrc)

                dishdata = {
                    'dishId': dishId,
                    'dishName': dish.get('dishName'),
                    'dishPrice': dish.get('dishPrice'),
                    'dishDesc': dish.get('dishDesc'),
                    'dishState': 'stay',
                    'checkFailDesc': '',
                    'dishUnit': dish.get('dishUnit'),
                    'dishSort': 1,
                    'createTime': now,
                    'updateTime': now,   
                    'menuNames': dish.get('menuNames'),
                    'classNames': dish.get('classNames'),   
                    'imageId': imageId
                }
                newList.append(dishdata)
                data = {
                    'diningNo': diningNo,
                    'stallNo': stallNo,
                    'dishList': newList
                }
                collection.insert_one(data)
                # 把该图片插入imageList集合里
                collectionImage = mg_client[dbSynPosDishes][collectionImageList]
                imageInfo = {
                    'imageId': imageId,
                    'imageSrc': dish.get('imageSrc')
                }
                collectionImage.insert_one(imageInfo)
                dishIdList.append(dishId)
            return dishIdList

        # 如果餐厅和档口存在该表中
        tempres = res.get('dishList')
        if tempres is not None:
            if len(tempres) > 0:
                newList = tempres
                for v in tempres:
                    for info in dishList:
                        if v['dishName'] == info.get('dishName'):
                            return False # 该菜名已存在

        for dish in dishList:
            dishId = getuuId()
            imageSrc = dish.get('imageSrc')
            imageId = ''
            if imageSrc is not None and len(imageSrc) > 200:
                imageSrc = globalBase64ImageScale(imageSrc)
                imageId = globalStrMd5(imageSrc)

            now = globalGetNowTime()
            data = {
                'dishId': dishId,
                'dishName': dish.get('dishName'),
                'dishPrice': dish.get('dishPrice'),
                'dishDesc': dish.get('dishDesc'),
                'dishState': 'stay',
                'checkFailDesc': '',
                'dishUnit': dish.get('dishUnit'),
                'dishSort': 1,
                'createTime': now,
                'updateTime': now,   
                'menuNames': dish.get('menuNames'),
                'classNames': dish.get('classNames'),   
                'imageId': imageId
            }
            newList.append(data)
            dishIdList.append(dishId)
            # 把该图片插入imageList集合里
            collectionImage = mg_client[dbSynPosDishes][collectionImageList]
            imageInfo = {
                'imageId': imageId,
                'imageSrc': dish.get('imageSrc')
            }
            collectionImage.insert_one(imageInfo)

        collection.find_one_and_update(cond, 
                    {'$set': 
                        {'dishList': newList} 
                    })
                    
        return dishIdList
        
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def editDish(diningNo, stallNo, dishId, dishName, dishPrice, dishUnit, classNames, menuNames, dishDesc, imageSrc):
    '''
    编辑菜品
    '''
    try:                            
        imageId = ''
        if len(imageSrc) > 200:
            imageSrc = globalBase64ImageScale(imageSrc)
            imageId = globalStrMd5(imageSrc)
            
        mg_client = get_mongo_client()
        collection = mg_client[dbSynPosDishes][collectionDishList]
        cond = {'diningNo': diningNo, 'stallNo': stallNo}
        res = collection.find_one(cond)
        # 该餐厅档口不存在
        if res is None:
            return None

        # 餐厅档口的菜品列表不存在
        newList = res.get('dishList')
        if res.get('dishList') is None or len(newList) <= 0:
            return None

        # 如果要编辑的菜的菜名已经存在了则不允许
        for n, v in enumerate(newList):
            if v['dishName'] == dishName and v['dishId'] != dishId:
                return False

        # 如果该餐厅的该档口的该菜品ID存在
        for n, v in enumerate(newList):
            if v['dishId'] == dishId:
                now = globalGetNowTime()
                # 如果改菜名 或者单价或者单位的时候   审核状态改为待审核状态
                if newList[n]['dishName'] != dishName or newList[n]['dishPrice'] != dishPrice or newList[n]['dishUnit'] != dishUnit:
                    newList[n]['dishState'] = "stay"
                
                newList[n]['dishId'] = dishId
                newList[n]['dishName'] = dishName
                newList[n]['dishPrice'] = dishPrice
                newList[n]['dishDesc'] = dishDesc
                newList[n]['updateTime'] = now
                newList[n]['dishUnit'] = dishUnit
                newList[n]['menuNames'] = menuNames
                newList[n]['classNames'] = classNames                     
                # 把该图片更新了，没有则更新
                collectionImage = mg_client[dbSynPosDishes][collectionImageList]
                if len(imageId) > 10:
                    newList[n]['imageId'] = imageId
                    collectionImage.find_one_and_update({'imageId': imageId}, 
                                        {'$set':                                   
                                            {'imageSrc': imageSrc}                                   
                                        }, upsert=True)

                return collection.find_one_and_update(cond, 
                                    {'$set': 
                                        {'dishList': newList}
                                    })

        return None    
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def delDish(diningNo, stallNo, dishId):
    '''
    删除指定菜品
    '''
    try:
        mg_client = get_mongo_client()
        collection = mg_client[dbSynPosDishes][collectionDishList]
        cond = {'diningNo': diningNo, 'stallNo': stallNo}
        res = collection.find_one(cond)
        # 该餐厅档口不存在
        if res is None:
            return None

        # 餐厅档口的菜品列表不存在
        newList = res.get('dishList')
        if res.get('dishList') is None or len(newList) <= 0:
            return None    

        for n, v in enumerate(newList):
            # 如果该餐厅的该档口的该菜品id存在
            if v['dishId'] == dishId:
                newList.remove(v)
                imageId = v.get('imageId')
                # 把该图片删除
                if imageId is not None and len(imageId) > 10:
                    collectionImage = mg_client[dbSynPosDishes][collectionImageList]
                    collectionImage.delete_one({'imageId': imageId})

                return collection.find_one_and_update(cond, 
                                    {'$set': 
                                        {'dishList': newList}                                  
                                    })
        
        return None
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def sortClass(diningNo, stallNo, classList):
    '''
    调整档口菜品类别排序
    '''
    try:
        mg_client = get_mongo_client()
        collection = mg_client[dbSynPosDishes][collectionDishList]
        cond = {'diningNo': diningNo, 'stallNo': stallNo}
        res = collection.find_one(cond)
        # 该餐厅档口不存在
        if res is None:
            return None

        return collection.find_one_and_update(cond, 
                            {'$set': 
                                {'classList': classList}                           
                            })    
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def sortDish(diningNo, stallNo, dishIds):
    '''
    调整菜品排序
    '''
    try:
        mg_client = get_mongo_client()
        collection = mg_client[dbSynPosDishes][collectionDishList]
        cond = {'diningNo': diningNo, 'stallNo': stallNo}
        res = collection.find_one(cond)
        # 该餐厅档口不存在
        if res is None:
            return None

        newList = res.get('dishList')
        if res.get('dishList') is None or len(newList) <= 0:
            return None

        # 只把排序字段更新
        for info in dishIds:
            for n, v in enumerate(newList):
                if v['dishId'] == info.get('dishId'):
                    newList[n]['dishSort'] = info.get('dishSort')
               
        return collection.find_one_and_update(cond, 
                            {'$set': 
                                {'dishList': newList}                          
                            })    
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def delDishs(diningNo, stallNo, dishIds):
    '''
    批量删除指定菜品
    '''
    try:
        mg_client = get_mongo_client()
        collection = mg_client[dbSynPosDishes][collectionDishList]
        cond = {'diningNo': diningNo, 'stallNo': stallNo}
        res = collection.find_one(cond)
        # 该餐厅档口不存在
        if res is None:
            return None

        # 餐厅档口的菜品列表不存在
        newList = res.get('dishList')
        if res.get('dishList') is None or len(newList) <= 0:
            return None    

        for id in dishIds:
            for n, v in enumerate(newList):
                if v['dishId'] == id:
                    imageId = v.get('imageId')
                    newList.remove(v)

                    if imageId is not None and len(imageId) > 10:
                        collectionImage = mg_client[dbSynPosDishes][collectionImageList]
                        collectionImage.delete_one({'imageId': imageId})

        return collection.find_one_and_update(cond, 
                            {'$set': 
                                {'dishList': newList}                                  
                            })
    except Exception as e:
        raise ErrMongoClient.data(str(e))
